package homework01;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "OrderServlet", value = "/OrderServlet")
public class OrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String[] productNames = request.getParameterValues("choice");
        HttpSession session = request.getSession();
        Product[] products = (Product[]) session.getAttribute("products");
        if (products == null) {
            // 初始化商品列表
            products = new Product[]{
                    new Product("香肠", 10.0, 100),
                    new Product("苹果", 5.0, 50),
                    new Product("酱油", 8.0, 30),
                    new Product("饮料", 3.0, 200)
            };
            session.setAttribute("products", products);
        }

        if (productNames != null) {
            for (String productName : productNames) {
                for (Product product : products) {
                    if (product.getName().equals(productName) && product.getStock() > 0) {
                        product.setStock(product.getStock() - 1); // 减少库存
                        session.setAttribute(productName, product); // 存储商品对象
                        break;
                    }
                }
            }
        }
        String url = "<A href='/homework01_war_exploded/CartServlet'><h2>欢迎去购物车页面!</h2></A>";
        response.getWriter().print("<h1>点击超链接，链接到购物车页面,去查看购物车中的商品。<br />" + url);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
